package com.icinfo.cloud.provider.punish.service.impl;

import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.constant.PunishMainServicePortUriConstant;
import com.icinfo.cloud.provider.common.dto.FileInfoSaveDto;
import com.icinfo.cloud.provider.common.enums.AttachmentRequestContentTypeEnum;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.FileTransferFormEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.oss.service.IOssOperateService;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.PunishMainClientUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.config.dto.ConfigPaymentChannelInfoQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.vo.ConfigPaymentChannelInfoVo;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceRegisterDetailInfo;
import com.icinfo.cloud.provider.punish.dto.*;
import com.icinfo.cloud.provider.punish.external.dto.EntBaseInfoDto;
import com.icinfo.cloud.provider.punish.external.vo.EntBaseInfoVo;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartyTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.ucase.payment.model.CasePaymentResultRecord;
import com.icinfo.cloud.provider.punish.vo.*;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 简易处罚API对应的Service接口实现类
 * @Author zhengqiang
 * @Date 2022/6/14 14:30
 **/
@Slf4j
@Service
public class SimpleCaseApiServiceImpl implements ISimpleCaseApiService {

    @Resource
    private ICaseMainDetailSimpleInfoService caseMainDetailSimpleInfoService;
    @Resource
    private ISimpleCaseService simpleCaseService;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private IOssOperateService iOssOperateService;
    @Value("${member.url}")
    private String memberUrl;
    @Value("${member.api.downloadAnnexByAnnexUid}")
    private String downloadAnnexByAnnexUid;
    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CasePaymentResultRecordMapper casePaymentResultRecordMapper;
    @Resource
    private CaseSourceRegisterDetailInfoMapper caseSourceRegisterDetailInfoMapper;

    /**
     * 描述： 检验单位配置
     *
     * @author: zhengqiang
     * @date: 2022/7/21
     * @param: orgCode
     * @return {@link boolean}
     **/
    public boolean checkSysDepartParam(String orgCode) {
        List<LineTerritoryInfoVo> lineTerritoryInfoVos = sysDepartParamService.getLineInfoListByOrgCode(orgCode);
        if (ObjectUtils.isEmpty(lineTerritoryInfoVos)){
            throw new BusinessException("暂未配置条线信息，请联系管理员");
        }

        //缴款渠道配置校验
        ConfigPaymentChannelInfoQueryDto queryDto = new ConfigPaymentChannelInfoQueryDto();
        queryDto.setChannelNo("330000022");
        queryDto.setOrgCode(orgCode);
        Result result = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_PAYMENT_CHANNEL_CONFIG_INFO, queryDto);
        if (ObjectUtils.isEmpty(result) || HttpStatus.HTTP_OK != result.getCode() || ObjectUtils.isEmpty(result.getData())) {
            throw new BusinessException("缴款渠道配置不存在，请联系管理员");
        }
        List<ConfigPaymentChannelInfoVo> list = JSON.parseArray(result.getData().toString(), ConfigPaymentChannelInfoVo.class);
        if (ObjectUtils.isEmpty(list)) {
            throw new BusinessException("未找到缴款渠道相关配置信息【" + orgCode + "】");
        }
        return true;
    }


    /**
     * 描述： 简易案件创建完成
     *
     * @author: zhengqiang
     * @date: 2022/7/18
     * @param: saveDto
     * @return {@link SimpleCaseSaveVo}
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SimpleCaseSaveVo saveSimpleCaseInfo(SimpleCaseSaveDto saveDto) {
        //设置来源为快捷执法
        saveDto.setCaseSourceAppId("KJZF");
        //签名转base64
        if (!ObjectUtils.isEmpty(saveDto.getSignFingerprintPic())) {
            InputStream is = HttpUtil.createGet(saveDto.getSignFingerprintPic()).execute().bodyStream();
            // 文件转为base64
            saveDto.setSignFingerprintPic("data:image/jpg;base64," + Base64.encode(is));
        }

        //保存案件信息
        SimpleCaseSaveVo saveVo = simpleCaseService.saveCase(saveDto);
        saveVo.setCaseId(saveDto.getCaseId());
        return saveVo;
    }

    /**
     * 描述： 查询简易处罚文书
     *
     * @author: zhengqiang
     * @date: 2022/7/18
     * @param: caseId
     * @return {@link List< SimpleCaseDocVo>}
     **/
    @Override
    public List<SimpleCaseDocVo> saveSimpleCaseDoc(String caseId) {
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("案件id不能为空");
        }
        //查询文书是否已经生成,已生成则直接返回
        List<SimpleCaseDocVo> docVoList = getSimpleCaseDocByCaseId(caseId);
        if (!ObjectUtils.isEmpty(docVoList)) {
            return docVoList;
        }

        //历史数据重新生成文书
        dealSimpleCaseDocumentRecords(caseId);
        //组装简易处罚文书视图
        docVoList = getSimpleCaseDocByCaseId(caseId);
        return docVoList;
    }

    /**
     * 描述： 处理简易程序文书
     *
     * @author: zhengqiang
     * @date: 2022/9/7
     * @param: caseId
     * @return
     **/
    @Override
    public void dealSimpleCaseDocumentRecords(String caseId) {
        //查询简易处罚数据内容
        CaseMainDetailSimpleInfo detailSimpleInfo = caseMainDetailSimpleInfoService.getCaseMainDetailSimpleInfo(caseId);
        if (ObjectUtils.isEmpty(detailSimpleInfo)) {
            throw new BusinessException("未找到案件信息-caseId:" + caseId);
        }
        String caseContent = detailSimpleInfo.getCaseContent();
        SimpleCaseSaveDto dto = JSONObject.parseObject(caseContent, SimpleCaseSaveDto.class);
        dto.setCaseId(caseId);
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy年M月d日");
        String now = fmt.format(new Date());
        dto.setSignFingerprintDate(now);
        //调用生成文书方法
        simpleCaseService.dealSimpleCaseDocumentRecords(dto, Arrays.asList(DocumentKindEnum.DOC_KIND_XCZPJSM.getCode()));
    }

    /**
     * 根据caseId查询简易处罚文书
     *
     * @param caseId
     * @return
     */
    private List<SimpleCaseDocVo> getSimpleCaseDocByCaseId(String caseId){
        List<SimpleCaseDocVo> voList = new ArrayList<>();
        Example queryExample = new Example(CaseDocumentRecord.class);
        queryExample.createCriteria().andEqualTo("caseId", caseId).andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        List<CaseDocumentRecord> caseDocumentRecords = caseDocumentRecordMapper.selectByExample(queryExample);
        if (!ObjectUtils.isEmpty(caseDocumentRecords)) {
            //只返回简易程序处罚决定书
            caseDocumentRecords.forEach(e -> {
                //查询文书种类
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(e.getDocumentCatalogCode());
                String kindCode = detailByDocumentCatalogCode.getDocumentKindCode();
                if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(kindCode)) {
                    SimpleCaseDocVo vo = new SimpleCaseDocVo();
                    BeanUtils.copyProperties(e, vo);
                    voList.add(vo);
                }
            });

        }
        return voList;
    }

    /**
     * 描述： 外部系统简易处罚暂存
     *
     * @author: zhengqiang
     * @date: 2022/8/15
     * @param: saveDto
     * @return {@link int}
     **/
    @Override
    public int saveSimpleCaseTemporary(SimpleCaseSaveOfAppDto saveDto) {
        log.info("检查转简易处罚-saveSimpleCaseTemporary-入参: {}", saveDto);
        SimpleCaseSaveDto simpleCaseSaveDto = new SimpleCaseSaveDto();
        BeanUtils.copyProperties(saveDto, simpleCaseSaveDto);
        simpleCaseSaveDto.setIsAutoSave(Constant.STRING_0);
        //检查照片处理
        dealPhotoList(simpleCaseSaveDto.getCaseEvidencePhotoList());
        //当事人为企业,法人证件号或社会信用代码为空,调用接口补充法人证件号
        dealLegalInfo(simpleCaseSaveDto);
        //删除当前用户当前机构历史暂存数据
        dealTemporaryCaseData();
        //处理检查信息
        dealCheckTaskInfo(saveDto);
        return simpleCaseService.saveTemporary(simpleCaseSaveDto);
    }

    /**
     * 删除当前用户历史暂存数据
     */
    @Override
    public void dealTemporaryCaseData() {
        UserDTO userInfo = UserUtil.getUserInfo();
        List<String> temporarySimpleCaseList = caseMainInfoMapper.getTemporarySimpleCaseByUser(userInfo.getOrgCode(), userInfo.getUserId().toString());
        if (ObjectUtils.isEmpty(temporarySimpleCaseList)) {
            return;
        }

        for (String caseId : temporarySimpleCaseList) {
            //已缴款的数据不处理
            Example e = new Example(CasePaymentResultRecord.class);
            e.createCriteria().andEqualTo("caseId", caseId).andEqualTo("isDelete", YesOrNoEnum.NO.getCode());
            e.setOrderByClause("create_time desc");
            List<CasePaymentResultRecord> list = casePaymentResultRecordMapper.selectByExample(e);
            if (!ObjectUtils.isEmpty(list)) {
                continue;
            }
            simpleCaseService.deleteCaseInfo(caseId);
        }
    }

    /**
     * 补充当事人(法人)信息
     *
     * @param saveDto
     */
    private void dealLegalInfo(SimpleCaseSaveDto saveDto) {
        if (PartyTypeEnum.LEGAL.getCode().equals(saveDto.getPartyType())
                && (ObjectUtils.isEmpty(saveDto.getLegalCertNo()) || ObjectUtils.isEmpty(saveDto.getUniscid())) ) {
            EntBaseInfoDto entBaseInfoDto = new EntBaseInfoDto();
            if (!ObjectUtils.isEmpty(saveDto.getUniscid())) {
                entBaseInfoDto.setTyxydm(saveDto.getUniscid());
            }

            if (ObjectUtils.isEmpty(saveDto.getUniscid()) && !ObjectUtils.isEmpty(saveDto.getEntName())) {//社会信用代码为空使用企业名称
                entBaseInfoDto.setFrmc(saveDto.getEntName());
            }
            Result<JSONObject> entResult = PunishMainClientUtil.httpPost(PunishMainServicePortUriConstant.GET_ENT_INFO, entBaseInfoDto);
            if (!ObjectUtils.isEmpty(entResult)) {
                EntBaseInfoVo entInfo = JSONObject.parseObject(entResult.getData().toJSONString(), EntBaseInfoVo.class);
                if (!ObjectUtils.isEmpty(entInfo)) {
                    if (ObjectUtils.isEmpty(saveDto.getLegalCertNo())) {
                        saveDto.setLegalCertNo(entInfo.getFrZjhm());
                    }
                    if (ObjectUtils.isEmpty(saveDto.getUniscid())) {
                        saveDto.setUniscid(entInfo.getTyxydm());
                    }
                }
            }
        }
    }

    /**
     * 检查转简易处罚照片处理
     *
     * @param caseEvidencePhotoList
     */
    private void dealPhotoList(List<CaseEvidencePhotoDto> caseEvidencePhotoList) {
        if (!ObjectUtils.isEmpty(caseEvidencePhotoList)) {
            caseEvidencePhotoList.forEach(p -> {
                if (!ObjectUtils.isEmpty(p.getFileUrl()) && p.getFileUrl().contains("taskCenter")) {
                    // http://59.202.42.163/api/v2/taskCenter/plan/pubAnnexUrl/downloadAnnexByAnnexUid?uid=B688A956C89D4FDEBCE9207829199278
                    String fileUrl=p.getFileUrl();
                    String uid=fileUrl.substring(fileUrl.lastIndexOf("/")+1);;
                    String newFileUrl=memberUrl.concat(downloadAnnexByAnnexUid)+"?uid="+uid;
                    log.info("dealPhotoList地址："+newFileUrl);
                    byte[] bytes = HttpUtil.createGet(newFileUrl).addHeaders(HeaderUtil.headerInfo()).execute().bodyBytes();
                    //上传oss
                    FileInfoSaveDto fileInfo = new FileInfoSaveDto();
                    fileInfo.setFileBytes(bytes);
                    fileInfo.setFileTransferForm(FileTransferFormEnum.FILE_TRANSFER_FORM_3.getCode());
                    fileInfo.setFileType(AttachmentRequestContentTypeEnum.png.getCode());
                    Result result = iOssOperateService.uploadFile(fileInfo);
                    if (!ObjectUtils.isEmpty(result) && HttpStatus.HTTP_OK == result.getCode()
                            && !ObjectUtils.isEmpty(result.getData())) {
                        String ossUrl = result.getData().toString();
                        p.setFileUrl(ossUrl);
                    }
                }
            });
        }
    }

    private void dealCheckTaskInfo(SimpleCaseSaveOfAppDto saveDto) {
        if (!ObjectUtils.isEmpty(saveDto.getCheckTaskNumber())) {
            //保存检查信息
            Example del = new Example(CaseSourceRegisterDetailInfo.class);
            del.createCriteria().andEqualTo("caseSourceId", saveDto.getDataSourceServiceId());
            caseSourceRegisterDetailInfoMapper.deleteByExample(del);
            //新增数据
            CaseSourceRegisterDetailInfo detailInfo = new CaseSourceRegisterDetailInfo();
            BeanUtils.copyProperties(saveDto, detailInfo);
            detailInfo.setId(BaseUtil.createUid());
            detailInfo.setCaseSourceId(saveDto.getDataSourceServiceId());
            caseSourceRegisterDetailInfoMapper.insertSelective(detailInfo);
        }
    }

}
